package zhishuang.wang.sansi.tools.code;

/**
 * @Author Zhishuang.Wang
 * @Date 2023/7/5 11:20
 * @Email 1406110602@qq.com
 */

import java.io.UnsupportedEncodingException;

public class CodeConversion {
    public CodeConversion() {
    }

    public static byte[] getUTF8BytesFromGBKString(String gbkStr) {
        int n = gbkStr.length();
        byte[] utfBytes = new byte[3 * n];
        int k = 0;

        for(int i = 0; i < n; ++i) {
            int m = gbkStr.charAt(i);
            if (m < 128 && m >= 0) {
                utfBytes[k++] = (byte)m;
            } else {
                utfBytes[k++] = (byte)(224 | m >> 12);
                utfBytes[k++] = (byte)(128 | m >> 6 & 63);
                utfBytes[k++] = (byte)(128 | m & 63);
            }
        }

        if (k < utfBytes.length) {
            byte[] tmp = new byte[k];
            System.arraycopy(utfBytes, 0, tmp, 0, k);
            return tmp;
        } else {
            return utfBytes;
        }
    }

    public static String gbkToUtf8Code(byte[] gbkBytes) {
        try {
            String gbk = new String(gbkBytes, "gbk");
            return new String(getUTF8BytesFromGBKString(gbk), "UTF-8");
        } catch (UnsupportedEncodingException var2) {
            var2.printStackTrace();
            return null;
        }
    }

    public static String utf8ToGbkCode(String utf8) {
        try {
            String utf8Str = new String(utf8.getBytes("UTF-8"));
            String unicode = new String(utf8Str.getBytes(), "UTF-8");
            return new String(unicode.getBytes("GBK"));
        } catch (UnsupportedEncodingException var3) {
            var3.printStackTrace();
            return null;
        }
    }
}
